(function ($) {
  "use strict";
  $.fn.toTop = function (option) {
    var self = $(this);
    option = $.extend({},option);
    self.animate({scrollTop: 0},300);
  }
  /*
  * author GL
  * params = {
  *   el 滚动目标
  *   navbar 导航条
  *   docH 内容区域
  * }
  * */
  $.scrollTarget = function (option) {
    var defaults = {
      el: $(".gzl-section"),
      navbar: $(".gzl-navbar"),
      docH: $(".doc-section"),
      anchor: []
    };
    var params = $.extend({},defaults,option);
    // 锚点
    $("li",params.navbar).each(function (i) {
      var target = $(this).data("target");
      if (target) {
        params.anchor[i] = {
          target: target,
          top: $(target).offset().top + params.el.scrollTop() - params.navbar.height()
        }
      }
    })
    // 滚动事件
    params.el.on("scroll", function () {
      var self = this;
      $.requestAnimationFrame(function () {
        var scrollT = self.scrollTop;
        var navT = params.navbar.parent().offset().top;
        var windowH = $(window).height() - $(".gzl-footer").height();
        var documentH = params.docH.outerHeight(true);
        var isLast = scrollT + windowH >= documentH;
        // 导航条浮动
        if (scrollT > scrollT + navT) {
          params.navbar.addClass("fixed").parent().css("padding-top",params.navbar.height());
        }else{
          params.navbar.removeClass("fixed").parent().css("padding-top",0);
        }
        // 导航条匹配锚点
        $.each(params.anchor,function (i) {
          if (scrollT + 1 >= params.anchor[i].top && !isLast) {
            $("[data-target='"+params.anchor[i].target+"']").addClass("active").siblings().removeClass("active");
          } else if (isLast) {
            $("[data-target='"+params.anchor[params.anchor.length-1].target+"']").addClass("active").siblings().removeClass("active");
          }
        })
      })
    })
    // 锚点索引
    $("li",params.navbar).on("click", function () {
      params.el.animate({scrollTop: params.anchor[$(this).index()].top},300);
    })
  }
})($);